package com.idconfirmsystem.fragment;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import net.tsz.afinal.FinalDb;

import org.apache.http.util.EncodingUtils;
import org.dom4j.DocumentException;
import org.kymjs.kjframe.http.HttpCallBack;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.idconfirmsystem.Conf;
import com.idconfirmsystem.R;
import com.idconfirmsystem.activity.TaskDetailActivity;
import com.idconfirmsystem.adapter.TaskAdapter;
import com.idconfirmsystem.model.QueryRet;
import com.idconfirmsystem.model.Task;
import com.idconfirmsystem.model.TaskList;
import com.idconfirmsystem.model.TaskQuery;
import com.idconfirmsystem.model.UserBean;
import com.idconfirmsystem.remote.ConfirmApi;
import com.idconfirmsystem.util.FileUtils;
import com.idconfirmsystem.util.XmlUtils;

@SuppressLint("InlinedApi")
public class TaskFragment extends Fragment implements
		android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener {

	List<Task> tdTasks = new ArrayList<Task>();// 今日任务
	QueryRet<TaskList> qRet;// 查询返回值
	TaskAdapter adapter;
	String taskTypeName;// 任务类型名称

	LinearLayout header;
	ListView tasklistView;
	private CountDownTimer timer;
	ProgressBar progressbar;
	SwipeRefreshLayout swipe;

	// FinalDb db;

	private TaskHandler myHandler = new TaskHandler();
	TaskQuery query;// 任务查询条件
	private String serviceMethod = "TaskService/getTaskList";

	private String taskType;// 任务类型:A早送 B晚接 C中调

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		Bundle args = getArguments();
		if (args != null) {
			taskType = args.getString("taskType");
			Conf.TaskConf.TaskType = taskType;
		}
	}

	public void loadTask(String taskType) {
		if (query == null) {
			query = new TaskQuery();
		}
		// query.setDepDate("20150901");
		query.setTaskType(taskType);
		query.setType(UserBean.getInstance().getType());
		if (query.getType() == "SY") {// 守押任务
			query.setClerkNo(UserBean.getInstance().getUserName());
		} else {
			query.setBranchNumber(UserBean.getInstance().getBranchNumber());
		}
		if (header != null) {
			if (taskType == "A") {
				taskTypeName = "早送任务";
			} else if (taskType == "B") {
				taskTypeName = "晚接任务";
			} else {
				taskTypeName = "中调任务";
			}
			((TextView) header.findViewById(R.id.tv_taskcode))
					.setText(taskTypeName);
		}
		ConfirmApi.queryData(query, serviceMethod, callBack);// 获取数据

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_task, container, false);
		initView(view);
		loadTask(taskType);
		return view;
	}

	public void refresh() {
		progressbar.setVisibility(View.GONE);
	}

	private void initView(View view) {
		// db = FinalDb.create(getActivity(), false);
		progressbar = (ProgressBar) view.findViewById(R.id.progressbar);
		tasklistView = (ListView) view.findViewById(R.id.tasklistView);
		tasklistView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getActivity(),
						TaskDetailActivity.class);
				Bundle bundle = new Bundle();
				Conf.TaskProcess.curTask=tdTasks.get(arg2);
				bundle.putString("taskid", tdTasks.get(arg2).getId());
//				Conf.TaskConf.TaskType = tdTasks.get(arg2).getTask_type();
//				Log.e("TTTTTT", tdTasks.get(arg2).getAae317());
				intent.putExtras(bundle);
				startActivity(intent);
			}
		});
		header = (LinearLayout) view.findViewById(R.id.taskhead);

		swipe = (SwipeRefreshLayout) view.findViewById(R.id.swipe);
		swipe.setOnRefreshListener(this);
		// 顶部刷新的样式
		swipe.setColorSchemeResources(android.R.color.holo_red_light,
				android.R.color.holo_green_light,
				android.R.color.holo_blue_bright,
				android.R.color.holo_orange_light);
		if (adapter == null) {
			adapter = new TaskAdapter(getActivity(), tasklistView);
			tasklistView.setAdapter(adapter);
		}
	}

	HttpCallBack callBack = new HttpCallBack() {
		@Override
		public void onFailure(int errorNo, String strMsg) {
			// TODO Auto-generated method stub
			super.onFailure(errorNo, strMsg);
			toast("查询失败，错误编码：" + errorNo + ",失败原因：" + strMsg);
		}

		@Override
		public void onFinish() {
			// TODO Auto-generated method stub
			super.onFinish();
		}

		@Override
		public void onSuccess(String t) {
			// TODO Auto-generated method stub
			super.onSuccess(t);
			try {
				System.out.println(t);
				qRet = XmlUtils.toBean(TaskList.class, t);
				myHandler.sendEmptyMessage(1001);// 更新列表
			} catch (DocumentException e) {
				e.printStackTrace();
			}
		}

	};

	public void updateData() {
		tdTasks = new ArrayList<Task>();
		if (qRet != null && qRet.getTotalnum() > 0) {
			tdTasks = qRet.getResult().getTasks();
		}
		if (qRet.getTotalnum() < 1 && qRet.getResult() != null) {
			if (qRet.getResult().getTasks() != null) {
				Task t = qRet.getResult().getTasks().get(0);
				if (t != null) {
					toast(t.getAae317());
				}
			}
		}
		if (tdTasks.size() <= 0) {
			// toast("查无"+taskTypeName);
		}

		adapter.resetData(tdTasks);
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
	}

	private void toast(String text) {
		Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT).show();
		
	}

	private class TaskHandler extends Handler {
		public TaskHandler() {
		}

		public TaskHandler(Looper looper) {
		}

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 1001:// 进入子任务列表
				updateData();
				break;

			default:
				break;
			}
		}

	}
}
